<?php

declare(strict_types = 1);

namespace Tools\DataStructure\Closure;

use Tools\DataStructure\Closure;

/**
 * Class ClosureList
 * @package Tools\DataStructure\Closure
 */
class ClosureList
{
    /**
     * @var array Closure list
     */
    protected array $closures;

    /**
     * ClosureList constructor.
     * @param array $closures []
     */
    public function __construct(array $closures = [])
    {
        $this->closures = $closures;
    }

    /**
     * Execute all closure.
     *
     * @return array
     */
    public function execute() : array
    {
        $result  = [];

        foreach ($this->closures as $key => $closure) {
            /** @var Closure $closure */
            $result[$key] = $closure->execute();
        }

        return $result;
    }

    /**
     * add a closure to instance
     *
     * @param Closure $closure
     */
    public function push(Closure $closure)
    {
        $this->closures[] = $closure;
    }

    /**
     * get and remove the first element
     *
     * @return Closure | null
     */
    public function shift() : Closure | null
    {
        return array_shift($this->closures);
    }

    /**
     * add a closure to instance
     *
     * @param $key
     * @param Closure $closure
     * @return void
     */
    public function put($key, Closure $closure)
    {
        $this->closures[$key] = $closure;
    }

    /**
     * get the element
     *
     * @param $key
     * @return Closure|null
     */
    public function get($key) : ? Closure
    {
        return $this->closures[$key] ?? null;
    }

    /**
     * clear the container
     */
    public function clear()
    {
        $this->closures = [];
    }

    /**
     * is empty
     *
     * @return bool
     */
    public function isEmpty() : bool
    {
        return count($this->closures) === 0;
    }
}
